# -*- coding: cp936 -*-
#Python远程控制开关机代码实现
import time
import os
import sys
import poplib
import smtplib
from email.header import decode_header
from email.mime.text import MIMEText
import email

def guanji():
    #此函数负责发送关机标题（即guan）给邮箱
    sent=smtplib.SMTP('smtp.163.com')
    sent.login('XXXX@163.com','XXXX')
    to=['XXXX@163.com','XXXX@qq.com','XXXX@qq.com']
    content=MIMEText('From Surker is Python 远程关机指令')
    content['Subject']='guan'
    content['From']='XXXX@163.com'
    content['To']=','.join(to)
    sent.sendmail('XXXX@163.com',to,content.as_string())
    sent.close
def chongqi():
    #此函数负责发送关机标题（即chong）给邮箱
    sent=smtplib.SMTP('smtp.163.com')
    sent.login('XXXX@163.com','XXXX')
    to=['XXXX@163.com','XXXX@qq.com','XXXX@qq.com']
    content=MIMEText('From Surker is Python ')
    content['Subject']='chong'
    content['From']='XXXX@163.com'
    content['To']=','.join(to)
    sent.sendmail('XXXX@163.com',to,content.as_string())
    sent.close
def read():
    #此函数负责读取邮件中的指令，指令为guan返回0，指令为chong返回1
    read=poplib.POP3('pop.163.com')
    read.user('XXXX@163.com')
    read.pass_('XXXX')
    tongji=read.stat()#返回邮箱基本统计信息
    str=read.top(tongji[0],0)#返回最近邮件信息
    str2=[]
    for x in str[1]:#编码与解码
           try:
            str2.append(x.decode())
           except:
             try:
              str2.append(x.decode('gbk'))
             except:
              str2.append((x.decode('big5')))
    msg=email.message_from_string('\n'.join(str2)) #把String的邮件转换成email.message实例
    biaoti=decode_header(msg['Subject'])
    if biaoti[0][1]:
        biaoti2=biaoti[0][0].decode(biaoti[0][1])
    else:
        biaoti2=biaoti[0][0]
        #此时成功获取到最近一封邮件的标题，即为biaoti2
        if biaoti2=="guan":
            return 0
        if biaoti2=="chong":
            return 1
        read.quit()

if __name__=='__main__': #当程序运行时，读取邮件
    while True:
        time.sleep(2)
        if read()==0:
            os.system('shutdown -s -t 120 -c "Python已执行指令即将关闭计算机"')
            break
        if read()==1:
            os.system('shutdown -r')
            break